<?php
namespace app\api\controller;

use think\Request;

class CheckOut extends BaseController
{
    public function set()
    {
        $data = [];
        $data['error'] = [];

        if (Request::instance()->isPost()) {
            $user_id = input('post.user_id');
            $room_id = input('post.room_id');
            $check_in_id = input('post.check_in_id');
            $check_in_contact = input('post.check_in_contact');
            $check_in_date = input('post.check_in_date');
            $check_in_deposit = input('post.check_in_deposit');
            $check_in_electricity = input('post.check_in_electricity');
            $check_in_mobile = input('post.check_in_mobile');
            $check_in_rent = input('post.check_in_rent');
            $check_in_water = input('post.check_in_water');
            $check_out_date = input('post.check_out_date');

            $check_in_date = strtotime($check_in_date);
            $check_out_date = strtotime($check_out_date);

            if ($check_out_date < $check_in_date) {
                $data['error']['message'] = '离开日期不能小于入住日期';
                $data['status'] = 428;
            }

            $check_in_model = model('CheckIn');

            $check_in_history_where = [
                'user_id' => $user_id,
                'room_id' => $room_id,
                'check_out_date' => ['>=', $check_out_date],
                'is_deleted' => '0'
            ];

            $check_in_history = $check_in_model->where($check_in_history_where)->find();

            if ($check_in_history) {
                $data['error']['message'] = '该离开日期已存在入住记录';
                $data['status'] = 428;
            }

            if (!$data['error']) {
                $check_in_model->save([
                    'check_in_contact' => $check_in_contact,
                    'check_in_date' => $check_in_date,
                    'check_in_deposit' => $check_in_deposit,
                    'check_in_electricity' => $check_in_electricity,
                    'check_in_mobile' => $check_in_mobile,
                    'check_in_rent' => $check_in_rent,
                    'check_in_water' => $check_in_water,
                    'check_out_date' => $check_out_date,
                    'check_in_status' => '0'
                ],['check_in_id' => $check_in_id]);
                $data['status'] = 200;
            }
        }

        return json($this->dataReturn($data));
    }

    public function get()
    {
        $data = [];

        if (Request::instance()->isPost()) {
            $check_in_id = input('post.check_in_id');

            $check_in_model = model('CheckIn');
            $data['check_out'] = $check_in_model->get(['check_in_id' => $check_in_id, 'is_deleted' => '0']);
            $data['check_out']['check_in_date'] = date('Y-m-d', $data['check_out']['check_in_date']);
            $data['status'] = 200;
        }

        return json($this->dataReturn($data));
    }
}